What's the best method to print out time in C in the format 2009‐08‐10
18:17:54.811
?
Atm, I have Thu Sep 9 11:10:08 2010
but can't figure out the above.
What's the best method to print out time in C in the format 2009‐08‐10
18:17:54.811
?
Atm, I have Thu Sep 9 11:10:08 2010
but can't figure out the above.
Use strftime().
#include <stdio.h>
#include <time.h>
int main()
{
time_t timer;
char buffer[25];
struct tm* tm_info;
time(&timer);
tm_info = localtime(&timer);
strftime(buffer, 25, "%Y:%m:%d%H:%M:%S", tm_info);
puts(buffer);
return 0;
}
For milliseconds part, have a look at this question. How to measure time in milliseconds using ANSI C?
You could use strftime
, but struct tm
doesn't have resolution for parts of seconds. I'm not sure if that's absolutely required for your purposes.
struct tm tm;
/* Set tm to the correct time */
char s[20]; /* strlen("2009-08-10 18:17:54") + 1 */
strftime(s, 20, "%F %H:%M:%s", &tm);
time.h
defines a strftime
function which can give you a textual representation of a time_t
using something like:
#include <stdio.h>
#include <time.h>
int main (void) {
char buff[100];
time_t now = time (0);
strftime (buff, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now));
printf ("%s\n", buff);
return 0;
}
but that won't give you sub-second resolution since that's not available from a time_t
. It outputs:
2010-09-09 10:08:34.000
If you're really constrained by the specs and do not want the space between the day and hour, just remove it from the format string.